package com.zhouyiquan.reggie.controller;

import com.zhouyiquan.reggie.common.CustomException;
import com.zhouyiquan.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: 周益全 (https://gitee.com/zfovikqdev928)
 * @BugFeedBackEmail: zfovikqdev928@126.com
 * @Date: Create in 2022-10
 * @Description: 文件上传与下载控制器
 * @Version:
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class FileUpLoadController {
    //照片存储的路径，配置文件在 yml
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) { //file入参名要和前端的name一致

        //截取图片的后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String FileName = UUID.randomUUID() + suffix;

        //创建存放照片的目录,basePath已在 yml 中配置
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //将上传的文件重命名并修改存储位置
        try {
            file.transferTo(new File(basePath + FileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(FileName);
    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {

            //读取图片
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出图片
            ServletOutputStream servletOutputStream = response.getOutputStream();


            //设置回响类型
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                servletOutputStream.write(bytes, 0, len);
                servletOutputStream.flush(); //刷新
            }
            //回收资源
            servletOutputStream.close();
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new CustomException("图片未找到");
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("响应回写图片失败");
        }


    }
}
